package com.yqg.protection.controller;

import cn.hutool.core.io.FileUtil;
import com.yqg.protection.mapper.FilesMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/files")
@Api(tags = "文件管理")
@Slf4j
public class FilesController {

    @Value("${files.upload.path}")
    private String fileUploadPath;

    @Value("${haikang.upload.path}")
    private String haikangDownloadPath;

    @Resource
    private FilesMapper fileMapper;
    /**
     *文件上传接口
     * @param file 前端传过来的文件
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ApiOperation("文件上传接口")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        log.info("上传文件：{}",file.getOriginalFilename() );
        //获取原始数据名
        String originalFilename = file.getOriginalFilename();
        //构造唯一的文件名（不能重复）
        assert originalFilename != null;
        int index = originalFilename.lastIndexOf(".");
        String extname = originalFilename.substring(index);//找到 . 的索引
        String fileName = originalFilename.substring(0,index);//分离 文件名
        String timestampStr = String.valueOf(System.currentTimeMillis());//当前时间戳
        String newFileName = fileName +timestampStr + extname;//原文件名加时间戳
        log.info("新文件名：{}", newFileName);
        //转存到本地
        String newPath = fileUploadPath + newFileName;//待修改
        File localFile = new File(newPath);
        File parentFile = localFile.getParentFile();
        if(!parentFile.exists()) {
            parentFile.mkdirs();
        }
        try {
            file.transferTo(new File(newPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return newPath;
    }

    /**
     * 文件下载接口   http://localhost:9096/file/{fileUUID}
     * @param fileUUID
     * @param response    1.在同一个网络下面 2.ping 对方IP 3.关闭防火墙
     * @throws IOException
     */
    @GetMapping("/download/{fileUUID}")
    @ApiOperation("文件下载接口")
    public void haikangDownload(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件的唯一标识码获取文件
        File uploadFile = new File(haikangDownloadPath + fileUUID);
        //设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

    @GetMapping("/codeDownload/{fileUUID}")
    @ApiOperation("二维码文件下载接口")
    public void codeDownload(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        //根据文件的唯一标识码获取文件
        File uploadFile = new File(fileUploadPath + fileUUID);
        //设置输出流的格式
        ServletOutputStream os = response.getOutputStream();
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileUUID, "UTF-8"));
        response.setContentType("application/octet-stream");

        //读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }

//    /**
//     * 通过文件的md5查询文件
//     * @param md5
//     * @return
//     */
//    private Files getFileByMd5(String md5){
//        //查询文件的md5是否存在
//        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("md5",md5);
//        List<Files> filesList = fileMapper.selectList(queryWrapper);
//        return filesList.size() == 0 ? null : filesList.get(0);
//
//    }
    /*
    @GetMapping("/delete")
    @ApiOperation("删除文件")
    public Result delete(@RequestParam String path) {
        try {
            Path thePath = Paths.get(path);
            Files.delete(thePath);
            System.out.println("文件已成功删除");
        } catch (Exception e) {
            System.err.println("删除文件时出错: " + e.getMessage());
            return Result.error("删除文件失败");
        }
        return Result.success();
    }
     */
}
